package com.ruyuan.eshop.common.utils;

import com.ruyuan.eshop.common.domain.DiffValue;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhonghuashishan
 * @version 1.0
 */
@Slf4j
public class DiffFieldUtil {

    public static List<DiffValue> buildDiffField(Object newObj, Object oldObj,
                                                          List<String> diffFields) {
        // oldObj 为null表示新增，如果newObj 与 oldObj 类型不同，则不处理
        if (!Objects.isNull(oldObj) && !newObj.getClass().equals(oldObj.getClass())) {
            return null;
        }
        List<DiffValue> diffValues = new ArrayList<>();

        Field[] newObjFields = newObj.getClass().getDeclaredFields();
        Field[] oldObjFields = null;
        if (!Objects.isNull(oldObj)) {
            oldObjFields = oldObj.getClass().getDeclaredFields();
        }

        for (int i = 0; i < newObjFields.length; i++) {
            Field newObjField = newObjFields[i];
            // 需要比较当前字段
            String fieldName = newObjField.getName();
            if (diffFields.contains(fieldName)){
                try {
                    Object newValue = newObjField.get(fieldName);
                    if (Objects.isNull(oldObjFields) || Objects.equals(oldObjFields[i].get(fieldName), newValue)){
                        DiffValue diffValue = new DiffValue();
                        diffValue.setField(fieldName);
                        diffValue.setOldValue(Objects.isNull(oldObjFields)?null:oldObjFields[i].get(fieldName));
                        diffValue.setNewValue(newValue);
                        diffValues.add(diffValue);
                    }
                } catch (IllegalAccessException e) {
                    log.error("获取字段值失败", e);
                }
            }
        }
        return diffValues;
    }
}
